//
//  SXDataConvertManager.m
//  iOS_Router_Runtime
//
//  Created by 王水鑫 on 2018/12/5.
//  Copyright © 2018年 王水鑫. All rights reserved.
//

#import "SXDataConvertManager.h"

@implementation SXDataConvertManager

// NSDictionary 转 jsonString
+ (NSString *)convertToJsonStringFromNSDictionary:(NSDictionary *)json {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:&error];
    if (error) {
        NSLog(@"json解析失败:%@", error);
        return nil;
    }
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return jsonString;
}

// jsonString 转 NSDictionary
+ (NSDictionary *)convertToNSDictionaryFromJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if (error) {
        NSLog(@"jsonString解析失败:%@", error);
        return nil;
    }
    return json;
}

//  汉字 转成 Pinyin - 如果原来是字母则不变
+ (NSString *)convertToPinyinFromChineseCharacters:(NSString *)chineseCharacters {
    NSString * pinyin;
    if ([chineseCharacters length]) {
        NSMutableString * ms = [[NSMutableString alloc] initWithString:chineseCharacters];
        /**
         *  在CoreFoundation中提供了CFStringTransform函数，但在Foundation中却没有相对应的方法
         *  Boolean CFStringTransform(CFMutableStringRef string, CFRange *range, CFStringRef transform, Boolean reverse);
         *  string - 要转换的string，比如要转换的中文，同时它是mutable的，因此也直接作为最终转换后的字符串
         *  range - 要转换的范围，同时输出转换后改变的范围，如果为NULL，视为全部转换
         *  transform - 指定要进行什么样的转换，这里可以指定多种语言的拼写转换
         *  reverse - 指定该转换是否必须是可逆向转换的
         *  如果转换成功就返回true，否则返回false
         *  要汉字转换到拼音，我们只需要将transform设定为kCFStringTransformMandarinLatin或者kCFStringTransformToLatin(kCFStringTransformToLatin也可适用于非汉字字符串)
        */
        CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformMandarinLatin, NO);
        CFStringTransform( (__bridge CFMutableStringRef)ms, 0, kCFStringTransformStripDiacritics, NO);
        pinyin = ms;
    }
    return pinyin;
}

// 汉字 转成 汉字拼音(带声调) - 如果原来是字母则不变
+ (NSString *)convertToPinyinToneFromChineseCharacters:(NSString *)chineseCharacters {
    NSString * pinyin;
    if ([chineseCharacters length]) {
        NSMutableString * ms = [[NSMutableString alloc] initWithString:chineseCharacters];
        CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformMandarinLatin, NO);
        pinyin = ms;
    }
    return pinyin;
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
// 获取汉字的首字母 - 非汉字自动屏蔽
+ (NSString *)getPinYinPrefixLetterFromChineseCharacters:(NSString *)chineseCharacters {
    NSMutableString * stringM = [NSMutableString string];
    for (int i = 0; i < [chineseCharacters length]; i ++) {
        NSString * tempCharacter = [chineseCharacters substringWithRange:NSMakeRange(i, 1)];
        if (![NSClassFromString(@"SXDataCheckManager") performSelector:@selector(checkChineseFromCharacter:) withObject:tempCharacter]) {
            break;
        }
        NSMutableString * mutableString = [NSMutableString stringWithString:tempCharacter];
        CFStringTransform((CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, false);
        mutableString = (NSMutableString *)[mutableString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
        mutableString = [[mutableString substringToIndex:1] mutableCopy];
        [stringM appendString:(NSString *)mutableString];
    }
    return stringM;
}
#pragma clang diagnostic pop

// 毫秒级时间戳(13位，type:长长整型)/1000，标准时间戳(10位，type:长长整型) 转 标准时间 (2019-01-01 15:44:56)
+ (NSString *)convertToStandardTimeFromTimestamp:(id)timestamp {
    NSString *timestampString = [NSString stringWithFormat:@"%@", timestamp];
    long long time = [timestampString longLongValue];
    if ([[NSNumber numberWithLongLong:time] stringValue].length == 13) {
        // 毫秒级 转成 标准级
        time = time / 1000;
    } else if ([[NSNumber numberWithLongLong:time] stringValue].length != 10) {
        NSString *error = @"时间戳长度不对";
        return error;
    }
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // hh表示:12小时制,HH表示:24小时制
    NSString *standardTime = [formatter stringFromDate:date];
    return standardTime;
}

// 标准时间(2019-01-01 15:44:56) 转 标准时间戳(10位，type：NSString)
+ (NSString *)convertToTimestampFromStandardTime:(NSString *)standardTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // hh表示:12小时制,HH表示:24小时制
    //设置时区,这个对于时间的处理很重要
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    // 开始时间转换
    NSDate *date = [formatter dateFromString:standardTime];
    NSString *dateString = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    return dateString;
}

// NSData转换为UIImage
+ (UIImage *)convertToImageFromData:(NSData *)imageData {
    UIImage *image = [UIImage imageWithData:imageData];
    return image;
}

// UIImage转换为NSData
+ (NSData *)convertToDataFromImage:(UIImage *)image {
    NSData *imageData = UIImagePNGRepresentation(image);
    return imageData;
}

// 16进制颜色设置color
+ (UIColor *)convertToColorFromHexString:(NSString *)hexColor {
    NSString *cString = [[hexColor stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    // 判断前缀
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    // 从六位数值中找到RGB对应的位数并转换
    NSRange range;
    range.location = 0;
    range.length = 2;
    //R、G、B
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}

// 获取固定message显示到控件上所占size.width
+ (CGFloat)convertToContentWidthOfSizeFromTextMessage:(NSString *)message font:(UIFont *)font maxWidth:(CGFloat)maxWidth {
    CGSize size = [message sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    if (!maxWidth) {
        maxWidth = 0;
    }
    CGFloat width = size.width <= maxWidth ? size.width : maxWidth;
    return width;
}

// 获取固定message显示到控件上所占size.height
+ (CGFloat)convertToContentHeightOfSizeFromTextMessage:(NSString *)message font:(UIFont *)font maxWidth:(CGFloat)maxWidth {
    CGFloat contentW = [SXDataConvertManager convertToContentWidthOfSizeFromTextMessage:message font:font maxWidth:maxWidth];
    contentW = contentW <= [UIScreen mainScreen].bounds.size.width - 40 ? contentW : [UIScreen mainScreen].bounds.size.width - 40;
    CGRect rect = [message boundingRectWithSize:CGSizeMake(contentW, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil] context:nil];
    return rect.size.height;
}

@end
